import React from 'react';
import { IPublicModelPluginContext } from '@alilc/lowcode-types';
import { Button, Icon } from '@alifd/next';
import WrapperDialog from './components/WrapperDialog';
import ViewDialog from './components/ViewDialog';

/**
 * 自定义组件插件
 */
const CustomComponentPlugin = (ctx: IPublicModelPluginContext) => {
  return {
    async init() {
      const { skeleton } = ctx;

      // 用于存储对话框状态的全局对象
      const dialogState = {
        wrapperVisible: false,
        viewVisible: false,
        forceUpdate: () => {},
      };

      // 添加"封装组件"按钮到顶部导航栏
      skeleton.add({
        area: 'topArea',
        type: 'Widget',
        name: 'wrapComponent',
        content: () => {
          const [visible, setVisible] = React.useState(false);

          React.useEffect(() => {
            dialogState.wrapperVisible = visible;
            dialogState.forceUpdate = () => setVisible(!visible);
          }, [visible]);

          return (
            <>
              <Button
                type="primary"
                size="small"
                onClick={() => setVisible(true)}
              >
                封装组件
              </Button>
              <WrapperDialog
                ctx={ctx}
                visible={visible}
                onClose={() => setVisible(false)}
              />
            </>
          );
        },
        props: {
          align: 'right',
        },
      });

      // 添加"自定义组件"面板到左侧边栏
      skeleton.add({
        area: 'leftArea',
        type: 'PanelDock',
        name: 'customComponentsPane',
        content: ViewDialog,
        contentProps: {
          ctx: ctx,
        },
        props: {
          align: 'top',
          icon: 'zujianku',
          description: '自定义组件',
        },
      });

      console.log('✅ 自定义组件插件初始化完成');
    },

    destroy() {
      console.log('自定义组件插件已销毁');
    },
  };
};

CustomComponentPlugin.pluginName = 'CustomComponentPlugin';
CustomComponentPlugin.meta = {
  dependencies: ['EditorInitPlugin'],
};

export default CustomComponentPlugin;
